# Copyright (c) 2017 Presto Labs Pte. Ltd.
# Author: jaewon

from termcolor import colored
import re
import sys


def _highlight_log_line(line):
  if not hasattr(_highlight_log_line, 'matcher'):
    _highlight_log_line.matcher = re.compile(
        r'^[WEF]([0-9]{4}) ([0-9]{2}):([0-9]{2}):([0-9]{2})\.([0-9]{6})')
  if _highlight_log_line.matcher.search(line):
    if line[0] == 'F':  # Fatal
      return '%s\n' % colored(line, 'yellow', attrs=['bold'])
    elif line[0] == 'E':
      return '%s\n' % colored(line, 'red')
    elif line[0] == 'W':
      return '%s\n' % colored(line, 'white')
  return '%s\n' % line


def print_log(path, data):
  prefix_nocolor = '%s' % path
  prefix = colored(prefix_nocolor, 'blue')

  if not data:
    return
  if data[-1] == '\n':
    data = data[:-1]
  for line in data.split('\n'):
    line_out = '%s %s' % (prefix, _highlight_log_line(line))
    sys.stdout.write(line_out)
  sys.stdout.flush()
